package com.lancoo.znbkxx.uis;

import android.Manifest;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.MenuItem;

import com.example.znbk.znbklibrary.base.BaseLongActivity;
import com.lancoo.cpbase.authentication.base.AddressOperater;
import com.lancoo.znbkxx.R;
import com.lancoo.znbkxx.beans.BaseInfoBean;
import com.lancoo.znbkxx.beans.FirstPageBean;
import com.lancoo.znbkxx.beans.UserInfoBean;
import com.lancoo.znbkxx.beans.WrongFragmentBean;
import com.lancoo.znbkxx.fragments.LearningAnalysisFragment;
import com.lancoo.znbkxx.fragments.PersonalCenterFragment;
import com.lancoo.znbkxx.fragments.ProblemTrainingFragment;
import com.lancoo.znbkxx.fragments.WrongQuestionFragment;
import com.lancoo.znbkxx.net.BaseApi;
import com.lancoo.znbkxx.net.FirstPageApi;
import com.lancoo.znbkxx.net.HardFragmentApi;
import com.lancoo.znbkxx.net.OnSuccessAndFaultListener;
import com.lancoo.znbkxx.net.OnSuccessAndFaultSub;
import com.lancoo.znbkxx.net.WrongFragmentApi;
import com.example.znbk.znbklibrary.util.LancooUtils;
import com.google.gson.Gson;
import com.lancoo.cpbase.authentication.base.CurrentUser;
import com.tt.SkEgnManager;
import com.tt.listener.OnInitEngineListener;
import com.tt.setting.EngineSetting;
import com.tt.widget.PermissionsManager;
import com.tt.widget.PermissionsResultAction;

import java.util.Arrays;
import java.util.List;

import wangguolongTest.FirstPageBkfxFragment;

/**
 * Create by TangJun on 2019/2/16
 */
public class PhoneMainActivity extends BaseLongActivity {
    private FirstPageBkfxFragment fragmentBkfx;
    private WrongQuestionFragment fragment2;
    private ProblemTrainingFragment fragment3;
    private LearningAnalysisFragment fragment4;
    private PersonalCenterFragment fragment5;
    private Fragment[] fragments;
    private int lastfragment;
    private BottomNavigationView navigation;
    private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
            = new BottomNavigationView.OnNavigationItemSelectedListener() {

        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            resetToDefaultIcon();
            switch (item.getItemId()) {
                case R.id.navigation_revision:
                    if(lastfragment != 0)
                    {
                        switchFragment(lastfragment,0);
                        lastfragment = 0;
                    }
                    item.setIcon(R.mipmap.one);
                    return true;
                case R.id.navigation_wrong:
                    if(lastfragment != 1)
                    {
                        switchFragment(lastfragment,1);
                        lastfragment = 1;
                    }
                    item.setIcon(R.mipmap.two);
                    return true;
                case R.id.navigation_train:
                    if(lastfragment != 2)
                    {
                        switchFragment(lastfragment,2);
                        lastfragment = 2;
                    }
                    item.setIcon(R.mipmap.three);
                    return true;
                case R.id.navigation_analysis:
                    if(lastfragment != 3)
                    {
                        switchFragment(lastfragment,3);
                        lastfragment = 3;
                    }
                    item.setIcon(R.mipmap.four);
                    return true;
                case R.id.navigation_personal:
                    if(lastfragment != 4)
                    {
                        switchFragment(lastfragment,4);
                        lastfragment = 4;
                    }
                    item.setIcon(R.mipmap.five);
                    return true;
            }
            return false;
        }
    };
    private void resetToDefaultIcon() {
        navigation.getMenu().findItem(R.id.navigation_revision).setIcon(R.mipmap.one_s);
        navigation.getMenu().findItem(R.id.navigation_wrong).setIcon(R.mipmap.two_s);
        navigation.getMenu().findItem(R.id.navigation_train).setIcon(R.mipmap.three_s);
        navigation.getMenu().findItem(R.id.navigation_analysis).setIcon(R.mipmap.four_s);
        navigation.getMenu().findItem(R.id.navigation_personal).setIcon(R.mipmap.five_s);
    }

    @Override
    protected int setLayout() {
        return R.layout.activity_phone_main;
    }

    @Override
    protected void initView() {

        Log.e("===initViewAA===","========加密结果================"+LancooUtils.getBase64StuID(UserInfoBean.StuId));
        UserInfoBean.Key = LancooUtils.getBase64StuID(UserInfoBean.StuId);
        /*******************************重新初始化赋值相关数据**************************************************/
        AddressOperater mAddress = new AddressOperater(this);
        String address = mAddress.getBaseAddress();
        UserInfoBean.GlobalGrade = CurrentUser.GlobalGrade;
        UserInfoBean.StuId = CurrentUser.UserID;
        UserInfoBean.UserName = CurrentUser.UserName;
        UserInfoBean.GroupName = CurrentUser.GroupName;
        UserInfoBean.GroupID = CurrentUser.GroupID;
        UserInfoBean.UserType = CurrentUser.UserType;
        UserInfoBean.SchoolID = CurrentUser.SchoolID;
        UserInfoBean.Token = CurrentUser.Token;
        UserInfoBean.PhotoPath = CurrentUser.PhotoPath;
        UserInfoBean.BaseAdress = address;
        UserInfoBean.StageNo = CurrentUser.StudyLevel;
        /*********************************************************************************/

        geBaseInfo();
        initFragment();

        navigation = findViewById(R.id.navigation);
        navigation.setItemIconTintList(null);
        navigation.setItemTextAppearanceActive(R.style.bottom_selected_text);
        navigation.setItemTextAppearanceInactive(R.style.bottom_normal_text);
        navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);

        requestAllPermissions();//初始化语音评测

    }

    public void geBaseInfo(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                OnSuccessAndFaultListener l = new OnSuccessAndFaultListener() {
                    @Override
                    public void onSuccess(String result) {//成功回调
                        Gson gson = new Gson();
                        final BaseInfoBean infoBean = gson.fromJson(result,BaseInfoBean.class);
                        Message msg =Message.obtain();
                        msg.obj = infoBean;
                        Log.i("tj_40",result);
                        msg.what = 4;   //标志消息的标志
                        handler.sendMessage(msg);
                    }
                    @Override
                    public void onFault(String errorMsg) {//失败的回调
                        Log.i("tj_41",errorMsg+CurrentUser.Token);
                        getFirstPage();
                    }
                };
                //todo
                //动态设置参数
                Log.e("geBaseInfo","============Token=======Token========"+UserInfoBean.Token);
                Log.e("geBaseInfo","============Token=======UseID========"+UserInfoBean.StuId);
                Log.e("geBaseInfo","============Token=======SubjectID========"+UserInfoBean.SubjectID);
                BaseApi.getBaseInfo(UserInfoBean.Key,UserInfoBean.StuId,UserInfoBean.Token,UserInfoBean.StuId,UserInfoBean.SubjectID,new OnSuccessAndFaultSub(l));

            }
        }).start();
    }
    public void getHardFragment() {
        Log.i("tj_h","121");
        new Thread(new Runnable() {
            @Override
            public void run() {
                OnSuccessAndFaultListener l = new OnSuccessAndFaultListener() {
                    @Override
                    public void onSuccess(String result) {//成功回调
                        Log.i("tj_h",result);
                        Gson gson = new Gson();
                        final WrongFragmentBean infoBean = gson.fromJson(result,WrongFragmentBean.class);
                        Message msg =Message.obtain();
                        msg.obj = infoBean;
                        Log.i("tj_h",infoBean.toString());
                        msg.what = 3;   //标志消息的标志
                        handler.sendMessage(msg);
                    }
                    @Override
                    public void onFault(String errorMsg) {//失败的回调
                        Log.i("tj",errorMsg);
                    }
                };
                /*
                * itemType==3 为难题
                * */
                String LphaseCode = "";
                Log.e("==难题传参===","===============UserInfoBean.GlobalGrade====================="+UserInfoBean.GlobalGrade);
                if(UserInfoBean.GlobalGrade.equals("K7")||UserInfoBean.GlobalGrade.equals("K8")||UserInfoBean.GlobalGrade.equals("K9")){
                    LphaseCode = "B";
                }else if(UserInfoBean.GlobalGrade.equals("K10")||UserInfoBean.GlobalGrade.equals("K11")||UserInfoBean.GlobalGrade.equals("K12")){
                    LphaseCode = "C";
                }else{
                    LphaseCode = "A";
                }
                Log.e("==难题传参===","===============UserInfoBean.StuId====================="+UserInfoBean.StuId);
                Log.e("==难题传参===","===============UserInfoBean.SchoolID====================="+UserInfoBean.SchoolID);
                Log.e("==难题传参===","===============UserInfoBean.CNTSubjectID====================="+UserInfoBean.CNTSubjectID);
                Log.e("==难题传参===","===============LphaseCode====================="+LphaseCode);
                HardFragmentApi.getHardFragmentInfo(UserInfoBean.Key,UserInfoBean.StuId,UserInfoBean.SchoolID,UserInfoBean.CNTSubjectID,LphaseCode,
                        "3",new OnSuccessAndFaultSub(l));


            }
        }).start();
    }
    public void getWrongFragment() {
        Log.i("tj_w","121");
        new Thread(new Runnable() {
            @Override
            public void run() {
                OnSuccessAndFaultListener l = new OnSuccessAndFaultListener() {
                    @Override
                    public void onSuccess(String result) {//成功回调
                        Log.i("tj_w",result);
                        Gson gson = new Gson();
                        final WrongFragmentBean infoBean = gson.fromJson(result,WrongFragmentBean.class);
                        Message msg =Message.obtain();
                        msg.obj = infoBean;
                        Log.i("tj_w",infoBean.toString());
                        msg.what = 2;   //标志消息的标志
                        handler.sendMessage(msg);
                    }
                    @Override
                    public void onFault(String errorMsg) {//失败的回调
                        Log.i("tj",errorMsg);
                    }
                };
                /*
                 * itemType==1 为错题
                 * */
                String LphaseCode = "";
                if(UserInfoBean.GlobalGrade.equals("K7")||UserInfoBean.GlobalGrade.equals("K8")||UserInfoBean.GlobalGrade.equals("K9")){
                    LphaseCode = "B";
                }else if(UserInfoBean.GlobalGrade.equals("K10")||UserInfoBean.GlobalGrade.equals("K11")||UserInfoBean.GlobalGrade.equals("K12")){
                    LphaseCode = "C";
                }else{
                    LphaseCode = "A";
                }
                WrongFragmentApi.getWrongFragmentInfo(UserInfoBean.Key,UserInfoBean.StuId,UserInfoBean.SchoolID,UserInfoBean.CNTSubjectID,LphaseCode,
                        "1",new OnSuccessAndFaultSub(l));


            }
        }).start();
    }

    public void getFirstPage(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                OnSuccessAndFaultListener l = new OnSuccessAndFaultListener() {
                    @Override
                    public void onSuccess(String result) {//成功回调
                        Log.e("getFirstPage","===备考复习列表请求========"+result);
                        Gson gson = new Gson();
                        final FirstPageBean infoBean = gson.fromJson(result,FirstPageBean.class);
                        Message msg =Message.obtain();
                        msg.obj = infoBean;
                        Log.i("tj_f",infoBean.toString());
                        msg.what = 1;   //标志消息的标志
                        handler.sendMessage(msg);
                    }
                    @Override
                    public void onFault(String errorMsg) {//失败的回调
                        Log.i("tj",errorMsg);
                    }
                };
                //todo
                FirstPageApi.getFirstPageInfo(UserInfoBean.Key,UserInfoBean.SchoolID,UserInfoBean.SubjectID, UserInfoBean.GlobalGrade, UserInfoBean.CourseClassID,
                UserInfoBean.StuId, "0","","-1","0","0","1","10",
                        new OnSuccessAndFaultSub(l));


            }
        }).start();
    }
    private void switchFragment(int lastfragment,int index)
    {
        FragmentTransaction transaction =getSupportFragmentManager().beginTransaction();
        transaction.hide(fragments[lastfragment]);//隐藏上个Fragment
        if(fragments[index].isAdded()==false)
        {
            transaction.add(R.id.ll_frag,fragments[index]);
        }
        transaction.show(fragments[index]).commitAllowingStateLoss();


    }
    private void initFragment() {
        fragmentBkfx = new FirstPageBkfxFragment();
        fragment2 = new WrongQuestionFragment();
        fragment3 = new ProblemTrainingFragment();
        fragment4 = new LearningAnalysisFragment();
        fragment5 = new PersonalCenterFragment();
        fragments = new Fragment[]{fragmentBkfx,fragment2,fragment3,fragment4,fragment5};
        lastfragment=0;
        getSupportFragmentManager().beginTransaction().replace(R.id.ll_frag,fragmentBkfx).show(fragmentBkfx).commit();

    }


    /*********************************/
    public static String PaperId = "paperId";
    public static String getPaperId() {
        return PaperId;
    }
    public static void setPaperId(String paperId) {
        PaperId = paperId;
    }
    /**********************************/

    public static int CNtxl_wrongIndex = 0;
    public static int CNtxlModel = -1;
    public static int getCNtxlModel() {
        return CNtxlModel;
    }
    public static void setCNtxlModel(int CNtxlModel) {
        PhoneMainActivity.CNtxlModel = CNtxlModel;
    }
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    FirstPageBean firstPageBean = (FirstPageBean)msg.obj;
                    fragmentBkfx.setList(firstPageBean);
                    setPaperId(firstPageBean.getPaperList().get(0).getPaperID());
                    break;
                case 2:
                    WrongFragmentBean wrongFragmentBean = (WrongFragmentBean)msg.obj;
                    fragment2.setText(wrongFragmentBean);
                    fragment2.setList(wrongFragmentBean);
                    Log.e("onResume测试", "=====AAA=============WrongFragmentBean=============");
                    fragment2.setCurrentCNtxl();
                    break;
                case 3:
                    WrongFragmentBean hardFragmentBean = (WrongFragmentBean)msg.obj;
                    fragment3.setText(hardFragmentBean);
                    fragment3.setList(hardFragmentBean);
                    break;
                case 4:
                    final BaseInfoBean baseInfoBean = (BaseInfoBean)msg.obj;
                    Log.i("tj__baseInfor",baseInfoBean.toString());

                    final Handler mH = new Handler();
                    mH.post(new Runnable() {
                        @Override
                        public void run() {
                            if(baseInfoBean!=null&&baseInfoBean.getData().size()>0){
                                Log.e("GlobalGrade","========getGlobalGrade========AAAA1111111==11========="+baseInfoBean.getData().get(0).getGlobalGrade());
                                UserInfoBean.CourseClassID = baseInfoBean.getData().get(0).getCourseClassID();
                                Log.e("CourseClassID","========CourseClassID========AAAA1111111==222========="+UserInfoBean.CourseClassID);
                                getFirstPage();
                                mH.removeCallbacks(this);
                            }else{
                                mH.post(this);
                            }
                        }
                    });
                    break;
            }
        }
    };

    @Override
    public void onBackPressed() {
        Log.e("back","========AAACCC=============返回back=====");
        finish();
    }

    private void requestAllPermissions() {
        Log.e("requestAllPermissions","===================进入初始化语音评测初始化程序==================");
        //初始化语音识别引擎
        final EngineSetting setting = EngineSetting.getInstance(getApplicationContext());
        setting.setVADEnabled(true);
        setting.setOnInitEngineListener(new OnInitEngineListener() {
            @Override
            public void onStartInitEngine() {
                LancooUtils.showShort(PhoneMainActivity.this,"开始初始化引擎");
            }

            @Override
            public void onInitEngineSuccess() {
                LancooUtils.showShort(PhoneMainActivity.this,"初始化引擎成功");
            }

            @Override
            public void onInitEngineFailed() {
                LancooUtils.showShort(PhoneMainActivity.this,"初始化引擎失败");
            }
        });

        PermissionsManager.getInstance().requestPermissionsIfNecessaryForResult(this,
                new String[]{Manifest.permission.RECORD_AUDIO, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_PHONE_STATE}, new PermissionsResultAction() {

                    @Override
                    public void onGranted() {
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                SkEgnManager.getInstance(getApplicationContext()).initCloudEngine("148757611600000f", "2d5356fe1d5f3f13eba43ca48c176647", "userId", setting);
                            }
                        }).start();
                    }

                    @Override
                    public void onDenied(String permission) {

                    }
                });
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        PermissionsManager.getInstance().notifyPermissionsChange(permissions, grantResults);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        SkEgnManager.getInstance(this).recycle();
    }


    private boolean isFirstInto = true;
    @Override
    protected void onResume() {
        super.onResume();
        if(!isFirstInto) {
            Log.e("onResume测试", "===================刷新当前列表=====Activity=============");
            if (lastfragment == 0) {
                fragmentBkfx = new FirstPageBkfxFragment();
                fragments = new Fragment[]{fragmentBkfx,fragment2,fragment3,fragment4,fragment5};
                switchFragment(lastfragment, 0);
                getSupportFragmentManager().beginTransaction().replace(R.id.ll_frag,fragmentBkfx).show(fragmentBkfx).commit();
            } else if (lastfragment == 1) {
                fragment2 = new WrongQuestionFragment();
                fragments = new Fragment[]{fragmentBkfx,fragment2,fragment3,fragment4,fragment5};
                switchFragment(lastfragment, 1);
                getSupportFragmentManager().beginTransaction().replace(R.id.ll_frag,fragment2).show(fragmentBkfx).commit();
            } else if (lastfragment == 2) {
                fragment3 = new ProblemTrainingFragment();
                fragments = new Fragment[]{fragmentBkfx,fragment2,fragment3,fragment4,fragment5};
                switchFragment(lastfragment, 2);
                getSupportFragmentManager().beginTransaction().replace(R.id.ll_frag,fragment3).show(fragmentBkfx).commit();
            }
        }else {
            isFirstInto = false;
        }
    }
}

